<?php

namespace App\Http\Controllers;

use App\Http\Requests\ResourceUploadRequest;
use App\Models\Resource;
use App\Models\User;
use App\Models\UserDcoinsLog;
use App\Models\UserPointsLog;
use App\Models\UserDownloadLog;
use App\Models\UserVipFreeOpeCountLog;
use App\Models\UserVipInfo;
use App\Models\VipBaseInfo;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
use Laracasts\Flash\Flash;

class ResourcesController extends Controller
{

    public function upload(ResourceUploadRequest $request)
    {
        if ($request->file('resource')->isValid()) {
            try {
                $userId = \Auth::user()->id;
                // 获取上传文件并保存
                $file = $request->file('resource');
                $originName = $file->getClientOriginalName();
                $filename = Str::random(32) . '.' . $file->extension();
                $filePath = storage_path('app/public/uploads/resources/' . $userId . '/');

                $file->move($filePath, $filename);
                // 保存文件名到数据库
                $resource = Resource::create([
                    'file_name' => $filename,
                    'origin_name' => $originName,
                    'cost' => 0,
                    'topic_id' => 0,
                    'type' => 0,
                    'cost_type' => 0,
                    'category' => 0,
                    'user_id' => Auth::user()->id,
                    'file_path' => $filePath
                ]);
                // 返回响应
                return ['id' => $resource->id];
            } catch (\Throwable $e) {
                return ['error' => '上传失败，请稍后重试！'];
            }
        }
        return ['error' => '上传失败，请稍后重试！'];
    }

    public function download($id)
    {
        $resource = Resource::query()->find($id);

        if (!is_null($resource)) {
            /** @var User $user */
            $user = Auth::user();
            if ($user->isVip()) {
                return $this->vipDownload($resource, $user);
            } else {
                return $this->notVipDownload($resource, $user->id);
            }
        }
        // 资源不存在,报 404
        return response()->view('errors.404');//abort(404);
    }

    /**
     * @param $resource
     * @param User $user
     * @return \Symfony\Component\HttpFoundation\BinaryFileResponse
     */
    private function vipDownload($resource, $user)
    {
        $user_id = $user->id;
        /** @var UserVipInfo $userVipInfo */
        $userVipInfo = $user->vipInfo();

        // 获取下载记录
        $log = UserDownloadLog::hadDownloadedInWeek($user->id, $resource->id);
        //获取用户vip免费下载记录
        $vipFreeCountLog = UserVipFreeOpeCountLog::getLatestLog($user->id);
        // 未曾下载或下载记录已超过一周
        if (is_null($log) && $resource->user_id != $user_id) {
            //资源价值类型为积分
            if ($resource->cost_type == 1) {
                //vip 免积分
                if ($vipFreeCountLog->free_resource_remain_count > 0)
                {
                    $newVipFreeCountLog = new UserVipFreeOpeCountLog();
                    $newVipFreeCountLog->user_id = $user->id;
                    $newVipFreeCountLog->ope = UserVipFreeOpeCountLog::EXPEND_OPE;
                    $newVipFreeCountLog->free_home_help_ope_count = 0;
                    $newVipFreeCountLog->free_home_help_remain_count = $vipFreeCountLog->free_home_help_remain_count;
                    $newVipFreeCountLog->free_resource_ope_count = 1;
                    $newVipFreeCountLog->free_resource_remain_count = --$vipFreeCountLog->free_resource_remain_count;
                    $newVipFreeCountLog->free_algorithm_sources_ope_count = 0;
                    $newVipFreeCountLog->free_algorithm_sources_remain_count = $vipFreeCountLog->free_algorithm_sources_remain_count;
                    $newVipFreeCountLog->resource_id = $resource->id;
                    $newVipFreeCountLog->remark = '下载资源';
                    $newVipFreeCountLog->save();
                }
                else
                {
                    $points = UserPointsLog::getLatestUPLog($user_id);
                    $discountPoints = $resource->cost * $userVipInfo->resource_discount;
                    if (is_null($points) || $points->remain_points < $discountPoints)
                    {
                        //D币或积分不足
                        return response()->view('errors.402');//abort('402');
                    }

                    // 新建扣费记录
                    $newPoints = new UserPointsLog();
                    $newPoints->user_id = $user_id;
                    $newPoints->type = 2;
                    $newPoints->points = -$discountPoints;
                    $newPoints->remain_points = $points->remain_points - $discountPoints;
                    $newPoints->reason_type = UserPointsLog::REASON_TYPE_DOWNLOAD_RESOURCE;
                    $newPoints->remark = '下载资源';
                    $newPoints->save();
                }

                // 新建增费记录
                $dl_user_points = UserPointsLog::getLatestUPLog($resource->user_id);
                $newPoints = new UserPointsLog();
                $newPoints->user_id = $resource->user_id;
                $newPoints->type = 1; //增加
                $newPoints->points = $resource->cost;
                $newPoints->remain_points = $dl_user_points->remain_points ?? 0 + $resource->cost;
                $newPoints->reason_type = UserPointsLog::REASON_TYPE_RESOURCE_DOWNLOADED;
                $newPoints->remark = '资源被下载';
                $newPoints->save();
            } //资源价值类型为D币
            elseif ($resource->cost_type == 2) {
                //vip 免D币
                if ($vipFreeCountLog->free_algorithm_sources_remain_count > 0) {
                    $newVipFreeCountLog = new UserVipFreeOpeCountLog();
                    $newVipFreeCountLog->user_id = $user->id;
                    $newVipFreeCountLog->ope = UserVipFreeOpeCountLog::EXPEND_OPE;
                    $newVipFreeCountLog->free_home_help_ope_count = 0;
                    $newVipFreeCountLog->free_home_help_remain_count = $vipFreeCountLog->free_home_help_remain_count;
                    $newVipFreeCountLog->free_resource_ope_count = 0;
                    $newVipFreeCountLog->free_resource_remain_count = $vipFreeCountLog->free_resource_remain_count;
                    $newVipFreeCountLog->free_algorithm_sources_ope_count = 1;
                    $newVipFreeCountLog->free_algorithm_sources_remain_count = --$vipFreeCountLog->free_algorithm_sources_remain_count;
                    $newVipFreeCountLog->resource_id = $resource->id;
                    $newVipFreeCountLog->remark = '下载算法';
                    $newVipFreeCountLog->save();
                }
                else
                {
                    $dcoins = UserDcoinsLog::getLatestUDcoinLog($user_id);
                    $discountDcoins = $resource->cost * $userVipInfo->algorithm_sources_discount;
                    // D 币不足返回错误
                    if ($resource->cost_type == 2 && (is_null($dcoins) || $dcoins->remain_dcoins < $discountDcoins))
                    {
                        //D币或积分不足
                        return response()->view('errors.402');//abort('402');
                    }

                    // 新建扣费记录
                    $newDcoins = new UserDcoinsLog();
                    $newDcoins->user_id = $user_id;
                    $newDcoins->type = 2;//减少
                    $newDcoins->dcoins = -$discountDcoins;
                    $newDcoins->remain_dcoins = $dcoins->remain_dcoins - $discountDcoins;
                    $newDcoins->reason_type = UserDcoinsLog::REASON_TYPE_DOWNLOAD_RESOURCE;
                    $newDcoins->remark = '下载资源';
                    $newDcoins->save();
                }

                //新建增费记录
                $dl_user_dcoins = UserDcoinsLog::getLatestUDcoinLog($user_id);
                $newDcoins = new UserDcoinsLog();
                $newDcoins->user_id = $resource->user_id;
                $newDcoins->type = 1;//增加
                $newDcoins->dcoins = $resource->cost;
                $newDcoins->remain_dcoins = $dl_user_dcoins->remain_dcoins ?? 0 + $resource->cost;
                $newDcoins->reason_type = UserDcoinsLog::REASON_TYPE_RESOURCE_DOWNLOADED;
                $newDcoins->remark = '资源被下载';
                $newDcoins->save();
            }
            // 新建下载记录
            UserDownloadLog::create(['user_id' => $user_id, 'resource_id' => $resource->id]);
        }

        $resource->download_count += 1;
        $resource->save();
        // 扣费成功或一周内下载过则下载资源
        return response()->download(
            $resource->file_path . $resource->file_name,
            $resource->origin_name
        );
    }

    private function notVipDownload($resource, $user_id)
    {
        // 获取下载记录
        $log = UserDownloadLog::hadDownloadedInWeek($user_id, $resource->id);
        // 未曾下载或下载记录已超过一周
        if (is_null($log) && $resource->user_id != $user_id) {
            //资源价值类型为积分
            if ($resource->cost_type == 1) {
                $points = UserPointsLog::getLatestUPLog($user_id);

                if ($resource->cost_type == 1 && (is_null($points) || $points->remain_points < $resource->cost)) {
                    //D币或积分不足
                    return response()->view('errors.402');//abort('402');
                }

                // 新建扣费记录
                $newPoints = new UserPointsLog();
                $newPoints->user_id = $user_id;
                $newPoints->type = 2;
                $newPoints->points = -$resource->cost;
                $newPoints->remain_points = $points->remain_points - $resource->cost;
                $newPoints->reason_type = UserPointsLog::REASON_TYPE_DOWNLOAD_RESOURCE;
                $newPoints->remark = '下载资源';
                $newPoints->save();

                // 新建增费记录
                $dl_user_points = UserPointsLog::getLatestUPLog($resource->user_id);
                $newPoints = new UserPointsLog();
                $newPoints->user_id = $resource->user_id;
                $newPoints->type = 1; //增加
                $newPoints->points = $resource->cost;
                $newPoints->remain_points = $dl_user_points->remain_points - $resource->cost;
                $newPoints->reason_type = UserPointsLog::REASON_TYPE_RESOURCE_DOWNLOADED;
                $newPoints->remark = '资源被下载';
                $newPoints->save();

            } //资源价值类型为D币
            elseif ($resource->cost_type == 2) {
                $dcoins = UserDcoinsLog::getLatestUDcoinLog($user_id);
                // D 币不足返回错误
                if ($resource->cost_type == 2 && (is_null($dcoins) || $dcoins->remain_dcoins < $resource->cost)) {
                    //D币或积分不足
                    return response()->view('errors.402');//abort('402');
                }

                // 新建扣费记录
                $newDcoins = new UserDcoinsLog();
                $newDcoins->user_id = $user_id;
                $newDcoins->type = 2;//减少
                $newDcoins->dcoins = -$resource->cost;
                $newDcoins->remain_dcoins = $dcoins->remain_dcoins - $resource->cost;
                $newDcoins->reason_type = UserDcoinsLog::REASON_TYPE_DOWNLOAD_RESOURCE;
                $newDcoins->remark = '下载资源';
                $newDcoins->save();

                //新建增费记录
                $dl_user_dcoins = UserDcoinsLog::getLatestUDcoinLog($user_id);
                $newDcoins = new UserDcoinsLog();
                $newDcoins->user_id = $resource->user_id;
                $newDcoins->type = 1;//增加
                $newDcoins->dcoins = $resource->cost;
                $newDcoins->remain_dcoins = $dl_user_dcoins->remain_dcoins + $resource->cost;
                $newDcoins->reason_type = UserDcoinsLog::REASON_TYPE_RESOURCE_DOWNLOADED;
                $newDcoins->remark = '资源被下载';
                $newDcoins->save();
            }

            // 新建下载记录
            UserDownloadLog::create(['user_id' => $user_id, 'resource_id' => $resource->id]);
        }

        $resource->download_count += 1;
        $resource->save();
        // 扣费成功或一周内下载过则下载资源
        return response()->download(
            $resource->file_path . $resource->file_name,
            $resource->origin_name
        );
    }
}
